const { ScreepsAPI } = require('screeps-api');
const fs = require('fs');

var express = require("express");
var app = express();
var hostName = '0.0.0.0';
var port = 8181;

function buildAPI(token) {
    return new ScreepsAPI({
        token: token,
        protocol: 'https',
        hostname: 'screeps.com',
        port: 443,
        path: '/',
    });
}

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get("/", function (req, res) {
    let token = req.query['token'];
    let type = req.query['type'];
    let key = req.query['key'];
    let shard = req.query['shard'];
    let api = buildAPI(token)

    let data = null;
    switch (type) {
        case 'memory':
            api.memory.get(key, shard)
                .then(memory => {
                    data = memory
                    res.send(data)
                })
                .catch(err => console.error(err));
            break;
        default:
            res.send("无效请求!")
            break;
    }

})

app.listen(port, hostName, function () {
    console.log(`服务器运行在http://${hostName}:${port}`);
});